package com.fpost.action;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.fpost.constants.ActionConstants;
import com.fpost.domain.Article;
import com.fpost.domain.ArticleComment;
import com.fpost.domain.ArticleRatingSummary;
import com.fpost.domain.ArticleVersion;
import com.fpost.form.ArticlePresentationForm;
import com.fpost.form.dto.ArticleCommentDTO;
import com.fpost.form.dto.ArticleDTO;
import com.fpost.form.dto.ArticleVersionDTO;
import com.fpost.manager.ArticleCommentManager;
import com.fpost.manager.ArticleManager;
import com.fpost.util.ActionUtils;
import com.fpost.util.CommonUtils;

public class ArticlePresentationAction extends Action {
	
	private static Logger log = Logger.getLogger(ArticlePresentationAction.class);

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		//set current path in session
		CommonUtils.setCurrentPathInSession(request, mapping);
		
		String forward = ActionConstants.SUCCESS;
		ArticlePresentationForm presentationForm = (ArticlePresentationForm) form;

		try {
			String articleIdStr = (String) request.getParameter("articleId");			
			if (articleIdStr != null) {				
				long articleId = Long.parseLong(articleIdStr);
				ArticleManager articleManager = new ArticleManager();
				if (articleManager.isCurrentArticleExists(articleId)){
					Article article = articleManager.getArticleByIdIncrementHitCount(
							articleId, request.getRemoteAddr());
					presentationForm.setArticleDTO(new ArticleDTO(article, false));	
					CommonUtils.saveIpAddress(articleId, request);
					forward = ActionConstants.SUCCESS;
				} else {
					ActionUtils.setErrorMessage(request, "error.article.not.found");
					forward = ActionConstants.FAILURE;
				}				
			} else {
				ActionUtils.setErrorMessage(request, "error.article.not.found");
				forward = ActionConstants.FAILURE;
			}
		} catch (NumberFormatException e) {
			log.error(e.getMessage(), e);
			ActionUtils.setErrorMessage(request, "error.article.not.found");
			forward = ActionConstants.FAILURE;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			forward = ActionConstants.SYSTEM_FAILURE;
		}

		return mapping.findForward(forward);
	}
	
}
